package xyz.missou.blog.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.text.SimpleDateFormat;
import java.util.Date;

public class QiniuPictureUtil {

    private static String accessKey;
    private static String secretKey;
    private static String bucket;
    private static String baseUrl;
    //默认不指定key的情况下，以文件内容的hash值作为文件名


    public static String getAccessKey() {
        return accessKey;
    }

    public static void setAccessKey(String accessKey) {
        QiniuPictureUtil.accessKey = accessKey;
    }

    public static String getSecretKey() {
        return secretKey;
    }

    public static void setSecretKey(String secretKey) {
        QiniuPictureUtil.secretKey = secretKey;
    }

    public static String getBucket() {
        return bucket;
    }

    public static void setBucket(String bucket) {
        QiniuPictureUtil.bucket = bucket;
    }

    public static String getBaseUrl() {
        return baseUrl;
    }

    public static void setBaseUrl(String baseUrl) {
        QiniuPictureUtil.baseUrl = baseUrl;
    }

    public static String uploadPicture(String filename,byte[] picture) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //key即为文件名，此处采用随机生成文件名
        String key = filename.substring(0,filename.lastIndexOf('.'))+ "-"+ ((int)Math.random()*100000000)+"-"+(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()))+filename.substring(filename.lastIndexOf('.'),filename.length());
        String url = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(picture, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            if (baseUrl.endsWith("/"))
                url=baseUrl + putRet.key;
            else
                url=baseUrl +"/"+ putRet.key;
        } catch (QiniuException ex) {
            return null;
        }
        return url;
    }
}
